package indi.service;

import java.util.Date;
import java.util.ArrayList;

import indi.Data.*;

public class LiscenceManager {

	//系统已注册数
	static int COUNTOFREGISTE = 0;
	//当前借阅证
	private ArrayList<BorrowBookLiscence> currentLiscence;
	
	
	//构造函数
	public LiscenceManager() {
		super();
		this.currentLiscence = new ArrayList<>();
		//!默认加入一个借阅证
		addLiscence(new BorrowBookLiscence(new Student("fang","Law")));
		
	}
	
	//添加借阅证
	public int addLiscence(BorrowBookLiscence liscence) {
		try {
			//计数器+1
			COUNTOFREGISTE++;
			//列表中添加借书证
			currentLiscence.add(liscence);
			return liscence.getId();
		}catch(Exception e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	//删除借阅证
	public boolean deleteLiscence(int liscenceId) {
		try {
			for(int i = 0; i<currentLiscence.size(); i++) {
				if(currentLiscence.get(i).getId() == liscenceId) {
					currentLiscence.remove(i);
					return true;
				}
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	//更新借阅证
	public boolean updateLiscence(int liscenceId) {
		return false;
	}
	//查询借阅证
	public BorrowBookLiscence queryLiscence(int liscenceId) {
		try {
			for(BorrowBookLiscence e:currentLiscence) {
				if(liscenceId == e.getId()) {
					return e;
				}
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}

	//为借阅证添加一条关联借阅记录
	public boolean addRelatedBook(BorrowBookLiscence liscence, RecordOfBorrow record) {

		try {
			liscence.addOneBorrowingRecord(record);
		}catch(Exception e) {
			e.printStackTrace();
		}
		return true;
	}
	//删除借阅证关联的借阅记录
	public boolean deRelatedRecord(BorrowBookLiscence currentLiscence, RecordOfBorrow record) {
		return currentLiscence.deleteRecord(record);
	}
	//判断借阅证是否有逾期记录
	public boolean haveOverdueRecord(BorrowBookLiscence liscence) {
		
		//获取当前借书证所有借书记录
		ArrayList<RecordOfBorrow> currentRecords = liscence.getCurrentRecords();
		//获取当前时间
		Date now = new Date();
		
		try {
			//遍历记录，判断时间之差是否小于规定时间
			for(RecordOfBorrow e:currentRecords) {
				//计算时间差=现在日期-书本上次借阅时期
				int diffrentDays =now.getDay() - e.getLastBorrowedTime().getDay();
				//判断时间差是否小于规定时间
				if(diffrentDays > BookManager.MAINTAINDAYS) {
					return true;
				}
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	//判断借阅证借书是否达到上限
	public boolean isReachUpperLimit(BorrowBookLiscence liscence) {
		return (liscence.getCurrentRecords().size() >= BookManager.UPPERLIMIT);
	}

	public static int getCOUNTOFREGISTE() {
		return COUNTOFREGISTE;
	}
	
	
}
